﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Peak.Core.DataInterfaces;
using Peak.Core;

namespace Peak.ApplicationServices
{
  public class PriorityUpdater : IPriorityUpdater
  {
    public Story Move(StoryFilter filter, Page<Story> page, int id, int newPosition)
    {      
      List<Story> list = new List<Story>(page.Results);
      Story s = page.Results.FirstOrDefault(f => f.Id == id);
      int index = list.IndexOf(s);
      if (index == newPosition)
        return s;
      
      list.Remove(s);
      list.Insert(newPosition, s);

      if (filter.SortDirection == SortDirection.Asc && newPosition == 0)
      {
        s.Priority = list[newPosition + 1].Priority - 1;
      }
      else if(filter.SortDirection == SortDirection.Desc && newPosition == list.Count-1)
      {
        s.Priority = list[newPosition - 1].Priority - 1;
      }
      else if (filter.SortDirection == SortDirection.Desc && newPosition == 0)
      {
        s.Priority = list[newPosition + 1].Priority + 1;
      }
      else if(filter.SortDirection == SortDirection.Asc && newPosition == list.Count - 1)
      {
        s.Priority = list[newPosition - 1].Priority + 1;
      }
      else
      {
        s.Priority = (list[newPosition - 1].Priority + list[newPosition + 1].Priority)/2;
      }

      page.Results = list.ToArray();
      return s;
    }
  }
}